package com.yanxinim.cn.ui.message.multi;

import android.content.Intent;
import android.content.res.ColorStateList;
import android.os.Bundle;
import android.os.Parcelable;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

import androidx.core.view.ViewCompat;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshListView;
import com.xuan.xuanhttplibrary.okhttp.HttpUtils;
import com.xuan.xuanhttplibrary.okhttp.callback.BaseCallback;
import com.xuan.xuanhttplibrary.okhttp.callback.ListCallback;
import com.xuan.xuanhttplibrary.okhttp.result.ArrayResult;
import com.xuan.xuanhttplibrary.okhttp.result.ObjectResult;
import com.xuan.xuanhttplibrary.okhttp.result.Result;
import com.yanxinim.cn.MyApplication;
import com.yanxinim.cn.R;
import com.yanxinim.cn.Reporter;
import com.yanxinim.cn.bean.Friend;
import com.yanxinim.cn.bean.RoomMember;
import com.yanxinim.cn.bean.message.MucRoom;
import com.yanxinim.cn.bean.message.MucRoomMember;
import com.yanxinim.cn.broadcast.MsgBroadcast;
import com.yanxinim.cn.broadcast.MucgroupUpdateUtil;
import com.yanxinim.cn.db.dao.FriendDao;
import com.yanxinim.cn.db.dao.RoomMemberDao;
import com.yanxinim.cn.helper.AvatarHelper;
import com.yanxinim.cn.helper.DialogHelper;
import com.yanxinim.cn.sortlist.BaseComparator;
import com.yanxinim.cn.sortlist.BaseSortModel;
import com.yanxinim.cn.store.adapter.RedPacketAdapter;
import com.yanxinim.cn.ui.base.BaseActivity;
import com.yanxinim.cn.ui.other.BasicInfoActivity;
import com.yanxinim.cn.util.AsyncUtils;
import com.yanxinim.cn.util.Base64;
import com.yanxinim.cn.util.Constants;
import com.yanxinim.cn.util.PreferenceUtils;
import com.yanxinim.cn.util.TimeUtils;
import com.yanxinim.cn.util.ToastUtil;
import com.yanxinim.cn.util.ViewHolder;
import com.yanxinim.cn.util.secure.RSA;
import com.yanxinim.cn.util.secure.chat.SecureChatUtil;
import com.yanxinim.cn.view.BannedDialog;
import com.yanxinim.cn.view.MergerStatus;
import com.yanxinim.cn.view.SelectionFrame;
import com.yanxinim.cn.view.SkinImageView;
import com.yanxinim.cn.view.SkinTextView;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import de.greenrobot.event.EventBus;
import okhttp3.Call;

/**
 * Features: 展示群成员
 * Features  禁言 && 删除群成员
 * Features: 群主对群内成员备注
 * <p>
 * 因为管理员也可以进入该界面进行前三种操作，且管理员需要显示userName 群主显示cardName 所以需要区分下
 * // Todo 当群组人数过多时，排序需要很久，先干掉排序功能，考虑替换排序规则
 */
public class GroupUsersActivity extends BaseActivity {
//    @BindView(R.id.iv_store_icon)
//    ImageView ivStoreIcon;
    @BindView(R.id.iv_title_left)
    SkinImageView ivTitleLeft;
    @BindView(R.id.tv_title_left)
    SkinTextView tvTitleLeft;
    @BindView(R.id.pb_title_center)
    ProgressBar pbTitleCenter;
    @BindView(R.id.tv_title_center)
    SkinTextView tvTitleCenter;
    @BindView(R.id.iv_title_center)
    ImageView ivTitleCenter;
    @BindView(R.id.iv_title_right)
    SkinImageView ivTitleRight;
    @BindView(R.id.iv_title_right_right)
    SkinImageView ivTitleRightRight;
    @BindView(R.id.tv_title_right)
    SkinTextView tvTitleRight;
    @BindView(R.id.mergerStatus)
    MergerStatus mergerStatus;
    @BindView(R.id.rv_data)
    RecyclerView rvData;
    private boolean isSearch;

    private List<RoomMember> mSortRoomMember;
    private List<RoomMember> mSearchSortRoomMember;
    private BaseComparator<RoomMember> mBaseComparator;

    private TextView mTextDialog;

    private String mRoomId;
    private boolean isLoadByService;
    private boolean isBanned;
    private boolean isDelete;
    private boolean isSetRemark;

    private RoomMember mRoomMember;
    private RoomMember selectedMember;
    private Map<String, String> mRemarksMap = new HashMap<>();
    private List<MucRoomMember> roomMembers;
    private RedPacketAdapter redPacketAdapter;
    private String userIdSelected = "";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_room_all_member_red_packet);
        ButterKnife.bind(this);
        mRoomId = getIntent().getStringExtra("roomId");
        userIdSelected = getIntent().getStringExtra("userId");
        isLoadByService = getIntent().getBooleanExtra("isLoadByService", false);
        isBanned = getIntent().getBooleanExtra("isBanned", false);
        isDelete = getIntent().getBooleanExtra("isDelete", false);
        tvTitleCenter.setText(R.string.group_member);
//        initActionBar();
        tvTitleRight.setText("确定");
        isSetRemark = getIntent().getBooleanExtra("isSetRemark", false);
        rvData.setLayoutManager(new LinearLayoutManager(this));
//        initData();
//        loadDataByService(false);
        loadMembers();
        tvTitleRight.setOnClickListener(v -> {
            Intent intent = getIntent();
            intent.putExtra("userId", selectedMember.getUserId());
            intent.putExtra("userName", selectedMember.getUserName());
            setResult(2021, intent);
            finish();
        });
        ivTitleLeft.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
    }

    private void initActionBar() {
        if (getSupportActionBar() != null){
            getSupportActionBar().hide();
            findViewById(R.id.iv_title_left).setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    finish();
                }
            });
            TextView tvTitle = (TextView) findViewById(R.id.tv_title_center);
            tvTitle.setText(R.string.group_member);
        }

    }

    private void initData() {
        AsyncUtils.doAsync(this, c -> {
            List<Friend> mFriendList = FriendDao.getInstance().getAllFriends(coreManager.getSelf().getUserId());
            for (int i = 0; i < mFriendList.size(); i++) {
                if (!TextUtils.isEmpty(mFriendList.get(i).getRemarkName())) {//针对该好友进行了备注
                    mRemarksMap.put(mFriendList.get(i).getUserId(), mFriendList.get(i).getRemarkName());
                }
            }
          /*  c.uiThread(r -> {
                mAdapter.notifyDataSetChanged();// 刷新页面
            });*/
        });

        mSortRoomMember = new ArrayList<>();
        mSearchSortRoomMember = new ArrayList<>();
        mBaseComparator = new BaseComparator<>();

        List<RoomMember> data = RoomMemberDao.getInstance().getRoomMember(mRoomId);
        mRoomMember = RoomMemberDao.getInstance().getSingleRoomMember(mRoomId, coreManager.getSelf().getUserId());

        mSortRoomMember.addAll(data);
        redPacketAdapter = new RedPacketAdapter(GroupUsersActivity.this, mSortRoomMember);
        redPacketAdapter.setAdapterOnClickListener(new RedPacketAdapter.AdapterOnClickListener() {
            @Override
            public void onClick(int position, RoomMember data) {
                if (userIdSelected != null && userIdSelected.equals(data.getUserId())) {
                    ToastUtil.showToast(GroupUsersActivity.this, "该成员已选择");
                } else {
                    selectedMember = data;
                    redPacketAdapter.updateItem(position, data);
                }

            }
        });
        rvData.setAdapter(redPacketAdapter);
    }



    private void loadDataByService(boolean reset) {
        Map<String, String> params = new HashMap<>();
        params.put("access_token", coreManager.getSelfStatus().accessToken);
        params.put("roomId", mRoomId);
        if (reset) {
            params.put("joinTime", String.valueOf(0));
        } else {
            long lastRoamingTime = PreferenceUtils.getLong(MyApplication.getContext(), Constants.MUC_MEMBER_LAST_JOIN_TIME + coreManager.getSelf().getUserId() + mRoomId, 0);
            params.put("joinTime", String.valueOf(lastRoamingTime));
        }
        params.put("pageSize", Constants.MUC_MEMBER_PAGE_SIZE);

        HttpUtils.get().url(coreManager.getConfig().ROOM_MEMBER_LIST)
                .params(params)
                .build()
                .execute(new ListCallback<MucRoomMember>(MucRoomMember.class) {
                    @Override
                    public void onResponse(ArrayResult<MucRoomMember> result) {

                        if (Result.checkSuccess(mContext, result)) {
                            List<MucRoomMember> mucRoomMemberList = result.getData();
                          /*  if (mucRoomMemberList.size() == Integer.valueOf(Constants.MUC_MEMBER_PAGE_SIZE)) {
                                mListView.setMode(PullToRefreshBase.Mode.BOTH);
                            } else {
                                mListView.setMode(PullToRefreshBase.Mode.PULL_FROM_START);
                            }*/
                            if (mucRoomMemberList.size() > 0) {
                                List<RoomMember> roomMemberList = new ArrayList<>();

                                for (int i = 0; i < mucRoomMemberList.size(); i++) {
                                    RoomMember roomMember = new RoomMember();
                                    roomMember.setRoomId(mRoomId);
                                    roomMember.setUserId(mucRoomMemberList.get(i).getUserId());
                                    roomMember.setUserName(mucRoomMemberList.get(i).getNickName());
                                    if (TextUtils.isEmpty(mucRoomMemberList.get(i).getRemarkName())) {
                                        roomMember.setCardName(mucRoomMemberList.get(i).getNickName());
                                    } else {
                                        roomMember.setCardName(mucRoomMemberList.get(i).getRemarkName());
                                    }
                                    roomMember.setRole(mucRoomMemberList.get(i).getRole());
                                    roomMember.setCreateTime(mucRoomMemberList.get(i).getCreateTime());
                                    roomMemberList.add(roomMember);
                                }


                                redPacketAdapter = new RedPacketAdapter(GroupUsersActivity.this, roomMemberList);
                                redPacketAdapter.setAdapterOnClickListener(new RedPacketAdapter.AdapterOnClickListener() {
                                    @Override
                                    public void onClick(int position, RoomMember data) {
                                        if (userIdSelected != null && userIdSelected.equals(data.getUserId())) {
                                            ToastUtil.showToast(GroupUsersActivity.this, "该成员已选择");
                                        } else {
                                            selectedMember = data;
                                            redPacketAdapter.updateItem(position, data);
                                        }

                                    }
                                });
                                rvData.setAdapter(redPacketAdapter);
                            }
                        }
                    }

                    @Override
                    public void onError(Call call, Exception e) {
                        ToastUtil.showErrorNet(getApplicationContext());
                    }
                });
    }
    MucRoom mucRoom;
    private MucRoomMember myself;// 自己
    private void loadMembers() {
        HashMap<String, String> params = new HashMap<>();
        params.put("roomId", mRoomId);

        HttpUtils.get().url(coreManager.getConfig().ROOM_GET)
                .params(params)
                .build()
                .execute(new BaseCallback<MucRoom>(MucRoom.class) {

                             @Override
                             public void onResponse(ObjectResult<MucRoom> result) {
                                 if (result.getResultCode() == 1 && result.getData() != null) {
                                     mucRoom = result.getData();
                                     myself = mucRoom.getMember();
                                     List<RoomMember> roomMemberList = new ArrayList<>();
                                     for (int i = 0; i < mucRoom.getMembers().size(); i++) {// 在异步任务内存储
                                         RoomMember roomMember = new RoomMember();
                                         roomMember.setRoomId(mucRoom.getId());
                                         roomMember.setUserId(mucRoom.getMembers().get(i).getUserId());
                                         roomMember.setUserName(mucRoom.getMembers().get(i).getNickName());
                                         if (TextUtils.isEmpty(mucRoom.getMembers().get(i).getRemarkName())) {
                                             roomMember.setCardName(mucRoom.getMembers().get(i).getNickName());
                                         } else {
                                             roomMember.setCardName(mucRoom.getMembers().get(i).getRemarkName());
                                         }
                                         roomMember.setRole(mucRoom.getMembers().get(i).getRole());
                                         roomMember.setCreateTime(mucRoom.getMembers().get(i).getCreateTime());
                                         roomMemberList.add(roomMember);
                                     }

                                     redPacketAdapter = new RedPacketAdapter(GroupUsersActivity.this, roomMemberList);
                                     redPacketAdapter.setAdapterOnClickListener(new RedPacketAdapter.AdapterOnClickListener() {
                                         @Override
                                         public void onClick(int position, RoomMember data) {
                                             if (userIdSelected != null && userIdSelected.equals(data.getUserId())) {
                                                 ToastUtil.showToast(GroupUsersActivity.this, "该成员已选择");
                                             } else {
                                                 selectedMember = data;
                                                 redPacketAdapter.updateItem(position, data);
                                             }

                                         }
                                     });
                                     rvData.setAdapter(redPacketAdapter);

                                 } else {
                                     ToastUtil.showErrorData(GroupUsersActivity.this);
                                 }
                             }

                             @Override
                             public void onError(Call call, Exception e) {
                                 ToastUtil.showErrorNet(GroupUsersActivity.this);
                             }
                         }
                );
    }

    private String getName(RoomMember member) {
        if (mRoomMember != null && mRoomMember.getRole() == 1) {
            if (!TextUtils.equals(member.getUserName(), member.getCardName())) {// 当userName与cardName不一致时，我们认为群主有设置群内备注
                return member.getCardName();
            } else {
                if (mRemarksMap.containsKey(member.getUserId())) {
                    return mRemarksMap.get(member.getUserId());
                } else {
                    return member.getUserName();
                }
            }
        } else {
            if (mRemarksMap.containsKey(member.getUserId())) {
                return mRemarksMap.get(member.getUserId());
            } else {
                return member.getUserName();
            }
        }
    }


}
